<?php

namespace common\base;

use Yii;
use yii\web\HttpException;
use yii\web\Response;

/**
 * ModelHttpException represents a "Method Not Allowed" HTTP exception with status code 405.
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ModelHttpException extends HttpException {

    /**
     * @var array list of HTTP status codes and the corresponding texts
     */
    public static $appExceptionCodes = [
        //401
        40101 => '微信授权失败',
        40102 => 'Switching Protocols',
        40103 => 'Switching Protocols',
        40028 => 'Switching Protocols',
        //401
        428 => '内容访问受限',
        418 => '内容访问受限',
        //500+
        534 => '数据保存失败',
        //400+
        416 => '数据初始化失败',
        406 => '信息验证失败',
        //10000+
        10003 => '内容访问受限',
        10004 => '微信授权失败',
    ];

    /**
     * ModelHttpException constructor.
     *
     * @param null $message
     * @param null $error
     * @param int $code
     * @param \Exception|null $previous
     */
    public function __construct($message = null, $error = null, $code = 428, \Exception $previous = null) {
        if (!empty($error)) {
            if (is_string($error)) {
                $append = $error;
            } elseif (is_array($error)) {
                $append = array_shift($error);
            } else {
                $append = print_r($error, true);
            }
            if ($message) {
                $message .= '，';
            }
            $message .= $append;
        }
        $status = $code > 999 ? intval($code / 100) : $code;
        parent::__construct($status, $message, $code, $previous);
    }

    /**
     * @return string the user-friendly name of this exception
     */
    public function getName() {
        if (isset(static::$appExceptionCodes[$this->code])) {
            return static::$appExceptionCodes[$this->code];
        }
        if (isset(Response::$httpStatuses[$this->statusCode])) {
            return Response::$httpStatuses[$this->statusCode];
        }
        return 'Error';
    }

}
